package top.kaoshanji.p1ch02d;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;

/**
 * author kaoshanji
 * ^_^
 * create time 2025/1/3 19:02
 */
public class MethodHandlesExample10 {

    private static final Logger logger = LogManager.getLogger(MethodHandlesExample10.class);

    public static void main(String[] args) throws Throwable {
        logger.info("...代码清单 p1ch02d-10：MethodHandles#guardWithTest的使用示例...");

        MethodHandles.Lookup lookup = MethodHandles.lookup();
        MethodHandle mhTest = lookup.findStatic(MethodHandlesExample10.class, "guardTest", MethodType.methodType(boolean.class));
        MethodType type = MethodType.methodType(int.class, int.class, int.class);

        MethodHandle mhTarget = lookup.findStatic(Math.class, "max", type);
        MethodHandle mhFallback = lookup.findStatic(Math.class, "min", type);
        MethodHandle mh = MethodHandles.guardWithTest(mhTest, mhTarget, mhFallback);
        int value = (int)mh.invoke(3, 5);

        System.out.println(value);

    }

    public static boolean guardTest() {
        return Math.random() > 0.5;
    }

}
